package com.cqw.exception;

import com.cqw.common.BaseResponse;
import com.cqw.common.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-04-30 14:39
 * @Description: 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class CommonExceptionHandler {


    @ExceptionHandler(Exception.class)
    public BaseResponse commonException(Exception ex) {
        log.error(ex.getMessage(), ex);
        //自定义异常
        if (ex instanceof CommonException) {
            CommonException commonException = (CommonException) ex;
            int errorCode = commonException.getCode() == null ? HttpStatus.ERROR : commonException.getCode();
            return BaseResponse.error(errorCode, commonException.getMessage());
        }

        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) ex;
            return BaseResponse.error(methodArgumentNotValidException.getBindingResult().getFieldError().getDefaultMessage());
        }

        return BaseResponse.error("系统繁忙", null);
    }


}
